package connection;

import java.sql.Connection;
import java.sql.DriverManager;

/**
 * 
 * This singleton class is responsible for obtaining a connection to the database.
 *
 */
public class ConnectionDB {

	private static ConnectionDB instance;
	private Connection con = null;

	private ConnectionDB() {
		try {
			// Register the JDBC driver for MySQL.
			Class.forName("com.mysql.jdbc.Driver");

			// Define URL of database server for
			// database named mysql on the localhost
			// with the default port number 3306.
			String url = "jdbc:mysql://localhost:3306/javatr";

			// Get a connection to the database for a
			// user named root with a blank password.
			// This user is the default administrator
			// having full privileges to do anything.
			con = DriverManager.getConnection(url, "root", "root");

		} catch (Exception e) {
			System.out.println("Something doesn't work..." + e);
		}

	}

	/**
	 * 
	 * @return a single connection to database
	 */
	public Connection getConnection() {
		return con;
	}
	
	/**
	 * 
	 * @return the instance of ConnectionDB class
	 */
	public static ConnectionDB getInstance() {
		if (instance == null) {
			instance = new ConnectionDB();
		}
		return instance;
	}

	
	/**
	 * Method to disconnect from the database.
	 */
	public void disconectDatabase() {
		instance = null;
		try {
			con.close();
		} catch (Exception e) {
		}
	}

}
